package com.xiaoran.rabbitmq.demo.config;

//确认回调方法

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MyCallback implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback{
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct//注入的注解
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }
    /**
     * correlationData::保存回调消息的ID及消息内容
     * ack：:返回成功（true）或失败（false）
     * cause：：失败的原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String ID=correlationData!=null?correlationData.getId():"";
            if(ack){
                System.out.println("交换机收到了消息：ID:"+ID);
            }else {
                System.out.println("交换机没有收到消息：ID："+ID+"。错误消息是："+cause);
            }
    }

    //可以在当消息传递过程中不可达目的的时候将消息返回给生产者
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        System.out.println("*****消息"+returned.getMessage()+"，被交换机+"+returned.getExchange()+"退回原因"+returned.getReplyText()+"是路由key"+returned.getRoutingKey());
    }
}
